<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户" prop="userId">
        <id-selector
          v-model="queryParams.userId"
          placeholder="请选择用户"
          dialog-title="选择用户"
          :api-function="listUser"
          :get-api-function="getUser"
          id-field="userId"
          name-field="userName"
          id-label="用户ID"
          name-label="用户名称"
          search-label="用户名称"
          search-placeholder="请输入用户名称"
          :extra-columns="[{prop: 'nickName', label: '用户昵称'}, {prop: 'email', label: '邮箱'}]"
        />
      </el-form-item>
      <el-form-item label="商品" prop="productId">
        <id-selector
          v-model="queryParams.productId"
          placeholder="请选择商品"
          dialog-title="选择商品"
          :api-function="listProduct"
          :get-api-function="getProduct"
          id-field="productId"
          name-field="productName"
          id-label="商品ID"
          name-label="商品名称"
          search-label="商品名称"
          search-placeholder="请输入商品名称"
          :extra-columns="[{prop: 'productCode', label: '商品编码'}, {prop: 'price', label: '价格'}]"
        />
      </el-form-item>
      <el-form-item label="SKU" prop="skuId">
        <id-selector
          v-model="queryParams.skuId"
          placeholder="请选择SKU"
          dialog-title="选择SKU"
          :api-function="listSku"
          :get-api-function="getSku"
          id-field="skuId"
          name-field="skuName"
          id-label="SKU ID"
          name-label="SKU名称"
          search-label="SKU名称"
          search-placeholder="请输入SKU名称"
          :extra-columns="[{prop: 'skuCode', label: 'SKU编码'}, {prop: 'price', label: '价格'}]"
        />
      </el-form-item>
      <el-form-item label="数量" prop="quantity">
        <el-input
          v-model="queryParams.quantity"
          placeholder="请输入数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="选中" prop="checked">
        <el-input
          v-model="queryParams.checked"
          placeholder="请输入是否选中"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fun:cart:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 参考其它页面（如 fun/order、fun/allCoupon），不为所有列显式设置宽度，保留至少一列为自适应列以填充剩余空间 -->
    <el-table
      v-loading="loading"
      :data="cartList"
      @selection-change="handleSelectionChange"
      style="width: 100%;"
      :fit="true"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="购物车ID" align="center" prop="cartId" width="100" />
      <!-- 组织、用户列保持固定最小宽度，避免过窄；但不全部列设置固定宽度，确保有列能自适应填充 -->
      <el-table-column label="创建组织" align="center" min-width="120">
        <template slot-scope="scope">
          <span>{{ getDeptName(scope.row.orgId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户" align="center" prop="userName" min-width="120" />
      <!-- 关键调整：去掉商品、SKU的(min-)width，让至少有一列成为“弹性列”，Element UI 会用它填满剩余宽度 -->
      <el-table-column label="商品" align="center" prop="productName" show-overflow-tooltip />
      <el-table-column label="SKU" align="center" prop="skuName" show-overflow-tooltip />
      <el-table-column label="数量" align="center" prop="quantity" width="80" />
      <el-table-column label="是否选中" align="center" prop="checked" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ec_currect_and_no" :value="scope.row.checked"/>
        </template>
      </el-table-column>
      <!-- 操作列已隐藏 -->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改购物车对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户" prop="userId">
          <id-selector
            v-model="form.userId"
            placeholder="请选择用户"
            dialog-title="选择用户"
            :api-function="listUser"
            :get-api-function="getUser"
            id-field="userId"
            name-field="userName"
            id-label="用户ID"
            name-label="用户名称"
            search-label="用户名称"
            search-placeholder="请输入用户名称"
            :extra-columns="[{prop: 'nickName', label: '用户昵称'}, {prop: 'email', label: '邮箱'}]"
          />
        </el-form-item>
        <el-form-item label="商品" prop="productId">
          <id-selector
            v-model="form.productId"
            placeholder="请选择商品"
            dialog-title="选择商品"
            :api-function="listProduct"
            :get-api-function="getProduct"
            id-field="productId"
            name-field="productName"
            id-label="商品ID"
            name-label="商品名称"
            search-label="商品名称"
            search-placeholder="请输入商品名称"
            :extra-columns="[{prop: 'productCode', label: '商品编码'}, {prop: 'price', label: '价格'}]"
          />
        </el-form-item>
        <el-form-item label="SKU" prop="skuId">
          <id-selector
            v-model="form.skuId"
            placeholder="请选择SKU"
            dialog-title="选择SKU"
            :api-function="listSku"
            :get-api-function="getSku"
            id-field="skuId"
            name-field="skuName"
            id-label="SKU ID"
            name-label="SKU名称"
            search-label="SKU名称"
            search-placeholder="请输入SKU名称"
            :extra-columns="[{prop: 'skuCode', label: 'SKU编码'}, {prop: 'price', label: '价格'}]"
          />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="是否选中" prop="checked">
          <el-input v-model="form.checked" placeholder="请输入是否选中" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCart, getCart, delCart, addCart, updateCart } from "@/api/fun/cart"
import { getDept } from "@/api/system/dept"
import CacheManager from '@/utils/cacheManager'
import { listUser, getUser } from "@/api/system/user"
import { listProduct, getProduct } from "@/api/fun/product"
import { listSku, getSku } from "@/api/fun/sku"
import IdSelector from '@/components/IdSelector'

export default {
  name: "Cart",
  dicts: ['ec_currect_and_no'],
  components: {
    IdSelector
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 购物车表格数据
      cartList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        productId: null,
        skuId: null,
        quantity: null,
        checked: null,
      },
    // API方法
    listUser,
    getUser,
    listProduct,
    getProduct,
    listSku,
    getSku,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        productId: [
          { required: true, message: "商品ID不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {    /** 根据部门ID获取部门名称 */
    getDeptName(deptId) {
      return CacheManager.getDeptName(deptId, getDept)
    },
    /** 查询购物车列表 */
    getList() {
      this.loading = true
      listCart(this.queryParams).then(response => {
        this.cartList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        cartId: null,
        userId: null,
        productId: null,
        skuId: null,
        quantity: null,
        checked: null,
        createTime: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.cartId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加购物车"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const cartId = row.cartId || this.ids
      getCart(cartId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改购物车"
      }).catch(error => {
        this.$modal.msgError("没有权限访问该数据")
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.cartId != null) {
            updateCart(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addCart(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const cartIds = row.cartId || this.ids
      this.$modal.confirm('是否确认删除购物车编号为"' + cartIds + '"的数据项？').then(function() {
        return delCart(cartIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fun/cart/export', {
        ...this.queryParams
      }, `cart_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped>
/* 确保表格在容器内 100% 拉伸 */
.app-container >>> .el-table {
  width: 100% !important;
}

/* 解决在某些布局下表格右侧留白的问题 */
.app-container {
  display: block;
}
</style>
